package com.example.demo.TakeMaterial.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.ResponseData;
import com.example.demo.TakeMaterial.dto.DeliveryInfo;
import com.example.demo.TakeMaterial.entity.MaterialRequisition;
import com.example.demo.TakeMaterial.entity.OutForm;
import com.example.demo.TakeMaterial.entity.RequisitionHeader;
import com.example.demo.TakeMaterial.mapper.OutFormMapper;
import com.example.demo.TakeMaterial.service.OutFormService;
import com.example.demo.TakeMaterial.service.RequisitionHeaderService;
import com.example.demo.entryWarehouse.entity.StoreInform;
import com.example.demo.entryWarehouse.service.StoreInformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;

@Service
public class OutFormServiceImpl extends ServiceImpl<OutFormMapper, OutForm> implements OutFormService {
    @Autowired
    private OutFormMapper outFormMapper;

    @Autowired
    StoreInformService storeInformService;

    @Autowired
    RequisitionHeaderService requisitionHeaderService;

    @Override
    public ResponseData selectAll() {
        List<OutForm> outFormList = outFormMapper.selectList(null);
        return ResponseData.buildOk(outFormList.size(), outFormList);
    }

    @Override
    public ResponseData selectThisMonth() {
        List<OutForm> outFormList = outFormMapper.selectThisMonth();
        return ResponseData.buildOk(outFormList.size(), outFormList);
    }

    // 发生错误时回滚
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData deliver(DeliveryInfo deliveryInfo) {
        QueryWrapper<StoreInform> queryWrapper = new QueryWrapper<>();
        UpdateWrapper<StoreInform> updateWrapper = new UpdateWrapper<>();
        RequisitionHeader requisitionHeader = deliveryInfo.getRequisitionHeader();
        List<OutForm> outFormList = new ArrayList<>();
        // 遍历materialRequisitionList，修改相应物料的库存，并生成outForm对象
        for (MaterialRequisition mrq : deliveryInfo.getMaterialRequisitionList()) {
            queryWrapper.eq("name", mrq.getName())
                    .eq("specification", mrq.getSpecification())
                    .eq("unit", mrq.getUnit());
            StoreInform storeInform = storeInformService.getOne(queryWrapper, false);
            if (storeInform == null) {
                // 手动回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseData.buildError("未查询到'" + mrq.getName() + "'的信息");
            }
            Integer num = mrq.getActualNum();
            if (num == null) {
                return ResponseData.buildError("请填写实际出库数量");
            }
            if (storeInform.getStoreNum() < num) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseData.buildError("物料'" + mrq.getName() + "'库存不足");
            }

            // 生成outForm对象
            OutForm outForm = new OutForm();
            outForm.setRequisitionId(mrq.getRequisitionId());
            outForm.setName(mrq.getName());
            outForm.setSpecification(mrq.getSpecification());
            outForm.setUnit(mrq.getUnit());
             outForm.setPosition(storeInform.getPosition());
            outForm.setOutNum(mrq.getActualNum());
            // 用途暂填为领料部门
            outForm.setPurpose(requisitionHeader.getDepartment());
            outForm.setReceiver(requisitionHeader.getReceiver());
            // 剩余库存，可以直接减去出库数量
            outForm.setStoreNum(storeInform.getStoreNum());
            outForm.setRemark(mrq.getReamrk());
            outFormList.add(outForm);

            updateWrapper.set("store_num", storeInform.getStoreNum() - mrq.getActualNum())
                    .eq("name", mrq.getName())
                    .eq("specification", mrq.getSpecification())
                    .eq("unit", mrq.getUnit());
            storeInformService.update(updateWrapper);
            queryWrapper.clear();
            updateWrapper.clear();
        }
        // 插入outFormList
        this.saveBatch(outFormList);

        // 修改requisitionHeader的状态
        UpdateWrapper<RequisitionHeader> headerUpdateWrapper = new UpdateWrapper();
        headerUpdateWrapper.set("status", "出库").eq("requisition_id", requisitionHeader.getRequisitionId());
        requisitionHeaderService.update(headerUpdateWrapper);
        // 传回本次的出库记录，前端使用Excel导出
        return ResponseData.buildOk("出库成功");
    }
}
